import React, { useState } from 'react';
import { useAntdTable } from 'ahooks';
import dayjs from 'dayjs';
import {
    Button,
    Form,
    Input,
    Row,
    message,
    Space,
    DatePicker,
    Table,
    Modal,
    Select,
    Col,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useFormModal } from '@/hooks/useFormModal';
import {
    mobilePhoneEdit,
    mobilePhoneAdd,
    mobilePhoneList,
    mobilePhoneOperateLog,
} from '@/config/request/manage';
import EditMobilePhoneInfo from './editMobilePhone/index';

import './index.scss';
import MobilePhoneOperateLog from './mobilePhoneOperateLog';

const MobilePhoneList: React.FC = () => {
    const [form] = Form.useForm();
    const formModalMobileInfo = useFormModal();
    const formModalMobileInfoLog = useFormModal();
    const [rowItem, setRowItem] = useState<any>();
    const [isEditInfo, setIsEditInfo] = useState(false);
    const [mobilePhoneOperateLogList, setMobilePhoneOperateLogList] = useState<
        any[]
    >([]);

    const mobileOperateStatusOptions = [
        { value: '1', label: '闲置' },
        { value: '2', label: '借用中' },
        { value: '3', label: '已损坏' },
        { value: '4', label: '维修中' },
        { value: '5', label: '已退回' },
    ];

    const mobileSystemOptions = [
        { value: 'Android', label: 'Android' },
        { value: 'IOS', label: 'IOS' },
        { value: 'Windows', label: 'Windows' },
        { value: 'Mac', label: 'Mac' },
        { value: 'Linux', label: 'Linux' },
    ];

    const { tableProps, search } = useAntdTable(
        async ({ pageSize, current: pageNum }) => {
            const { searchMobileUseDate } = form.getFieldsValue();
            const params = {
                ...form.getFieldsValue(),
                startTime: searchMobileUseDate?.[0]?.format(
                    'YYYY-MM-DD 00:00:00'
                ),
                endTime: searchMobileUseDate?.[1]?.format(
                    'YYYY-MM-DD 23:59:59'
                ),
                pageNum,
                pageSize,
            };
            delete params.searchMobileUseDate;
            const res = await mobilePhoneList(params);
            return {
                total: res.data.data?.total ?? 0,
                list: res.data.data?.list ?? [],
            };
        },
        { defaultPageSize: 10, form }
    );

    const columns: ColumnsType<any> = [
        {
            title: <span style={{}}>型号</span>,
            dataIndex: 'mobileType',
            key: 'mobileType',
            width: 50,
        },
        {
            title: '操作系统',
            dataIndex: 'mobileSystem',
            key: 'mobileSystem',
            width: 50,
        },
        {
            title: '状态',
            dataIndex: 'mobileOperateStatus',
            key: 'mobileOperateStatus',
            width: 20,
            render: (mobileOperateStatus: number) => {
                if (mobileOperateStatus === 1) {
                    return <span style={{ color: 'red' }}>{['闲置']}</span>;
                }
                if (mobileOperateStatus === 2) {
                    return <span style={{ color: 'green' }}>{['借用中']}</span>;
                }
                if (mobileOperateStatus === 3) {
                    return <span style={{ color: 'blue' }}>{['已损坏']}</span>;
                }
                if (mobileOperateStatus === 4) {
                    return <span style={{ color: 'blue' }}>{['维修中']}</span>;
                }
                return <span style={{ color: 'black' }}>{'已退回'}</span>;
            },
        },
        {
            title: '借用人',
            dataIndex: 'mobileUsePerson',
            key: 'mobileUsePerson',
            width: 30,
        },
        {
            title: '借用时间',
            dataIndex: 'mobileUseDate',
            key: 'mobileUseDate',
            width: 150,
            render: (text) =>
                text === null ? text : dayjs(text).format('YYYY-MM-DD'),
        },
        {
            title: '操作',
            dataIndex: 'a6',
            key: 'a6',
            width: 150,
            render: (text: string, record: any) => {
                return (
                    <Space size="middle">
                        <Button
                            type="primary"
                            onClick={() => {
                                setIsEditInfo(true);
                                setRowItem(record);
                                formModalMobileInfo.modal.open();
                            }}
                        >
                            编辑
                        </Button>
                        <Button
                            type="primary"
                            onClick={() => {
                                setIsEditInfo(true);
                                setRowItem(record);
                                getMobilePhoneOperateLog(record);
                                formModalMobileInfoLog.modal.open();
                            }}
                        >
                            操作日志
                        </Button>
                    </Space>
                );
            },
        },
    ];

    // 新增/修改供应商信息
    const editMobilePhoneInfo = async () => {
        try {
            const params = await formModalMobileInfo.form.validateFields();
            params.mobileUseDate = dayjs(params.mobileUseDate).format(
                'YYYY-MM-DD 00:00:00'
            );
            const response = isEditInfo
                ? await mobilePhoneEdit({
                      ...rowItem,
                      ...params,
                  })
                : await mobilePhoneAdd(params);
            if (response.data.code === 200) {
                message.success('保存成功！');
                formModalMobileInfo.modal.close();
                search.submit();
            }
        } catch (error: any) {
            console.error(error);
        }
    };

    const getMobilePhoneOperateLog = async (param: any) => {
        const response = await mobilePhoneOperateLog(param);
        if (response.data.code === 200) {
            setMobilePhoneOperateLogList(response.data.data.list);
        }
    };

    return (
        <div className="bg-white p-2.5">
            <Form form={form} name="supplierList_search">
                <Row>
                    <Col span={4}>
                        <Form.Item label="手机型号" name="mobileType">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item label="借用人" name="mobileUsePerson">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={3}>
                        <Form.Item label="操作系统" name="mobileSystem">
                            <Select
                                placeholder="请选择"
                                options={mobileSystemOptions}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={3}>
                        <Form.Item label="状态" name="mobileOperateStatus">
                            <Select
                                placeholder="请选择"
                                options={mobileOperateStatusOptions}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="借用时间" name="searchMobileUseDate">
                            <DatePicker.RangePicker
                                placeholder={['开始日期', '结束日期']}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={24} style={{ textAlign: 'right' }}>
                        <Form.Item>
                            <Space size="small">
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    onClick={search.submit}
                                >
                                    搜索
                                </Button>
                                <Button type="primary" onClick={search.reset}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                <div style={{ textAlign: 'left', marginBottom: 16 }}>
                    <Button
                        type="primary"
                        className="mt-5 mb-5"
                        onClick={() => {
                            setIsEditInfo(false);
                            setRowItem({});
                            formModalMobileInfo.modal.open();
                        }}
                    >
                        新增测试机
                    </Button>
                </div>

                <Table
                    {...tableProps}
                    bordered
                    columns={columns}
                    pagination={{
                        ...tableProps.pagination,
                        showQuickJumper: true,
                        showTotal: (total) => `总计 ${total} `,
                    }}
                    locale={{ emptyText: '暂无数据' }}
                />
            </Form>
            <Modal
                destroyOnClose
                open={formModalMobileInfo.isOpen}
                onOk={() => editMobilePhoneInfo()}
                onCancel={() => {
                    formModalMobileInfo.modal.close();
                }}
                title={isEditInfo ? '修改手机' : '新增手机'}
                className="mobileInfoModal"
                okText="确定"
                cancelText="取消"
                maskClosable={false}
            >
                <EditMobilePhoneInfo
                    formModal={formModalMobileInfo}
                    rowItem={rowItem}
                />
            </Modal>

            <Modal
                open={formModalMobileInfoLog.isOpen}
                onCancel={() => {
                    formModalMobileInfoLog.modal.close();
                }}
                onOk={() => {
                    formModalMobileInfoLog.modal.close();
                }}
                title={'操作日志'}
                className="mobileInfoLogModal"
                maskClosable={true}
            >
                <MobilePhoneOperateLog
                    formModal={formModalMobileInfoLog}
                    rowItem={rowItem}
                    dataList={mobilePhoneOperateLogList}
                />
            </Modal>
        </div>
    );
};

export default MobilePhoneList;
